package com.atguigu.flink0922.chapter07.state;

import com.atguigu.flink0922.bean.WaterSensor;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/6 14:32
 */
public class Flink03_State_Keyed_List {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        env
            .socketTextStream("hadoop162", 9999)  // 在socket终端只输入毫秒级别的时间戳
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private ListState<Integer> state;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    state = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("state", Integer.class));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    state.add(value.getVc()); // 个数(0,1,2,3) + 1  <= 4
                    
                    // 为了排序取前3, 需要把数据取出, 然后存入到一个java的集合中
                    final ArrayList<Integer> vcs = new ArrayList<>();
                    for (Integer vc : state.get()) {
                        vcs.add(vc);
                    }
                    vcs.sort((o1, o2) -> o2 - o1);
    
                    if (vcs.size() > 3) {
                        vcs.remove(3);  // 移除最后一个元素
                    }
                    state.update(vcs);
                    out.collect(ctx.getCurrentKey() + ": " + vcs);
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
